package com.example.myui.service;

import android.app.IntentService;
import android.content.Intent;
import android.support.annotation.Nullable;
import android.support.v4.content.LocalBroadcastManager;
import android.util.Log;

import com.example.myui.activity.AsyncActivity;

public class MyService extends IntentService {
    private static final String TAG = MyService.class.getSimpleName();
    private LocalBroadcastManager localBroadcastManager;

    public MyService() {
        super("MyService");
    }

    @Override
    public void onCreate() {
        super.onCreate();
        localBroadcastManager = LocalBroadcastManager.getInstance(this);
        sendServiceStatus("服务开始了");
    }

    @Override
    public int onStartCommand(@Nullable Intent intent, int flags, int startId) {
        String start = intent.getStringExtra("start");
        Log.i(TAG, "onStartCommand: " + start);
        return super.onStartCommand(intent, flags, startId);
    }

    @Override
    protected void onHandleIntent(@Nullable Intent intent) {
        sendThreadMsg("线程启动了");
        int progress = 0;
        try {
            while (progress < 50) {
                Thread.sleep(100);
                progress++;
                sendThreadMsg(progress + "");
            }
            sendThreadMsg("线程结束了");
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        sendServiceStatus("服务结束");
    }

    private void sendServiceStatus(String msg) {
        Intent intent = new Intent(AsyncActivity.ACTION_SERVICE);
        intent.putExtra("service", msg);
        localBroadcastManager.sendBroadcast(intent);
    }

    private void sendThreadMsg(String msg) {
        Intent intent = new Intent(AsyncActivity.ACTION_THREAD);
        intent.putExtra("thread", msg);
        localBroadcastManager.sendBroadcast(intent);
    }

}
